package com.jqsoft.launcher.activity.highblood;

import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.HBPPersonInfo;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.util.AndroidUtil;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**高血压筛选界面
 * @author gujunqi
 * date：2013-12-27 
 */
public class HBPScreenActivity extends JQActivity implements OnClickListener,OnScrollListener {
	private final String tag = "BphsLoginActivity";
	private ListView listview;// 列表
	private ListAdapter adapter;
	
	private LinearLayout ll_popup_xuanzhong;
	private LinearLayout ll_popup_chakan;
	private LinearLayout ll_popup_quxiao;

	private CheckBox xzCheckbox ,current_xzCheckbox;
	private PopupWindow popupWindow;
	private Button chaxuan_btn,totalcount_bt;
	private String content;
	private List<HBPPersonInfo> infoList = new ArrayList<HBPPersonInfo>();
	private boolean notfirstTime=false,isThreadrun=false;
	private long allcount=0;
	
	private View moreView;
	private LinearLayout progressBar_ll; // 更多等待层
	private Button moreButton,quezheng_btn;
//	private Handler handler = new Handler();
	@Override
	protected int getContentLayout() {
	
		return R.layout.hbp_screen_layout;
	}

	@Override
	protected void initGui() {
		listview = (ListView) findViewById(R.id.hbp_screen_lv);
		chaxuan_btn=(Button) findViewById(R.id.chaxuan_btn);
		chaxuan_btn.setOnClickListener(HBPScreenActivity.this);
		totalcount_bt=(Button) findViewById(R.id.totalcount_bt);
		quezheng_btn=(Button) findViewById(R.id.quezheng_btn);
		quezheng_btn.setOnClickListener(HBPScreenActivity.this);
		
	}

	@Override
	protected void initAction() {
		setGoBack();
		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// PopupWindow popupWindow = new
				// PopupWindow(AppManagerActivity.this);
				dismissPopupWindow();
				View contentView = View.inflate(getApplicationContext(),
						R.layout.popup_item, null);
				ll_popup_xuanzhong = (LinearLayout) contentView
						.findViewById(R.id.ll_popup_xuanzhong);
				ll_popup_chakan = (LinearLayout) contentView
						.findViewById(R.id.ll_popup_chakan);
				ll_popup_quxiao = (LinearLayout) contentView
						.findViewById(R.id.ll_popup_quxiao);
				xzCheckbox=(CheckBox) view.findViewById(R.id.xuanzhong_cb);
				ll_popup_xuanzhong.setOnClickListener(HBPScreenActivity.this);
				ll_popup_chakan.setOnClickListener(HBPScreenActivity.this);
				ll_popup_quxiao.setOnClickListener(HBPScreenActivity.this);
				LinearLayout ll_popup_container = (LinearLayout) contentView
						.findViewById(R.id.ll_popup_container);
				ScaleAnimation sa = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f);
				sa.setDuration(300);
//				Object obj = listview.getItemAtPosition(position);
//				if (obj instanceof AppInfo) {
//					AppInfo appinfo = (AppInfo) obj;
//					clickedpackname = appinfo.getPackname();
//					if (appinfo.isUserapp()) {
//						ll_uninstall.setTag(true);
//					} else {
//						ll_uninstall.setTag(false);
//					}
//				} else {
//					return;
//				}
				int top = view.getTop();
				int bottom = view.getBottom();            
				popupWindow = new PopupWindow(contentView, AndroidUtil.dip2px(getApplicationContext(), 400), bottom - top
						+ AndroidUtil.dip2px(getApplicationContext(), 40));
				// 注意:一定要给popwindow设置背景图片.背景资源.
				popupWindow.setBackgroundDrawable(new ColorDrawable(
						Color.TRANSPARENT));
				// 如果不设置背景资源 , 动画, 焦点的处理 都会产生问题.
				int[] location = new int[2];
				view.getLocationInWindow(location);
				popupWindow.showAtLocation(view, Gravity.TOP| Gravity.LEFT ,
						location[0] + 500, location[1]-20);
				ll_popup_container.startAnimation(sa);

			}
		});

		listview.setOnScrollListener(this);	
	}

	@Override
	protected void initData() {
		setTitle("高血压筛选");
		// ----------分页查询信息-----------------
		moreView = getLayoutInflater().inflate(
				R.layout.finance_fund_pagination_more, null);
		moreButton = (Button) moreView.findViewById(R.id.loadMore);
		moreButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			      if(notfirstTime&&(allcount>infoList.size())&&!isThreadrun)
			        {
			    	  moreButton.setVisibility(View.GONE);
			    	  progressBar_ll.setVisibility(View.VISIBLE);
//			    	  loadWaitPanel();
			        	//开线程去下载网络数据
//			    	  handler.postDelayed(sendable, 0);
			    	  new Thread(sendable).start();
			        }
				
			}
		});
		progressBar_ll = (LinearLayout) moreView.findViewById(R.id.progressBar_ll);

	}
	private Handler myhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.MSG_LOAD_OVER:
				adapter = new ListAdapter();
				notfirstTime=true;
				if(!(infoList.size()==allcount||allcount==0)){
//					listview.removeFooterView(moreView);
					listview.addFooterView(moreView);
				}
				listview.setAdapter(adapter);
				String count="共计"+allcount+"条）";
				totalcount_bt.setText("（已加载"+infoList.size()+"条/"+count);
				dismissrogressBar();
				break;
			case Constant.SHOW_UPDATE:
				totalcount_bt.setText("（已加载"+infoList.size()+"条/"+"共计"+allcount+"条）");
				if(infoList.size()>=allcount){
					 listview.removeFooterView(moreView);
				}else{
					progressBar_ll.setVisibility(View.GONE);
			    	  moreButton.setVisibility(View.VISIBLE);
				}
				adapter.notifyDataSetChanged();
				
//					dismissrogressBar();
				
				
				break;
			}
			isThreadrun=false;
		}
	};
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		   dismissPopupWindow();
		      if(firstVisibleItem+visibleItemCount==totalItemCount&&notfirstTime&&(allcount>infoList.size())&&!isThreadrun)
		        {
//		    	  loadWaitPanel();
//		        	//开线程去下载网络数据
//		    	  new Thread(sendable).start();
		        }
			}

	// 请求服务器
		private Runnable sendable = new Runnable() {

			public void run() {
				isThreadrun=true;
				String requestUrl = BphsURL.getCommonPath("GetHypertension_URL");
				String methodName = BphsURL.getCommonPath("GetHypertension_METHOD");
//				 String requestUrl = "http://60.171.146.122:9098/WebService/Andrews/HypertensionWebService.asmx";
				Log.i(tag, "查询:content" + requestUrl);
//				String methodName="GetHypertensionScreening";
				JSONObject data = new JSONObject();
				try {
					UserLoginInfo info = UserLoginInfo.getInstances();
					data.put("sAreaCode", info.getsManagementDivisionCode());// 
					data.put("iCurrentPageIndex", "1"); 
					data.put("iPageSize", "15"); // 
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
				content = WebServiceUtils.requestByParams(methodName, data.toString(), requestUrl);
				if (StringUtils.isNotBlank(content)) {
					  try {
							Log.i(tag, "返回的查询结果"+content);
//						 String result= content.replaceAll("\\\\", "");
//							Log.i(tag, "返回的查询结果"+result);
						JSONObject json = new JSONObject(content);
//						Log.i(tag, "返回的查询结果"+result);"AllCount":0,
//						allcount= 28;
						allcount= json.getLong("AllCount");
					JSONObject jo = new JSONObject(json.getString("Data"));
					 JSONArray jsonArray = (JSONArray) jo.get("Table");
			            for (int i = 0; i < jsonArray.length(); ++i) {
			                JSONObject o = (JSONObject) jsonArray.get(i);
			                HBPPersonInfo info =new HBPPersonInfo(o.getString("sNo"), o.getString("sPersonName"), o.getString("sSexName"),
			                		o.getString("dBirthday"),o.getString("sCardNo"),o.getString("dCheckTime"),o.getString("sHeadDoctorName"),
			                		o.getString("dBloodPressureLeftL"),o.getString("dBloodPressureLeftH"),o.getString("dBloodPressureRightL"),
			                		o.getString("dBloodPressureRightH"),
			                		o.getString("HealthyCheckUpCount"),
			                		o.getString("HighRisk"));
			    			infoList.add(info);
			            }} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					  if(notfirstTime){
						  myhandler.sendEmptyMessage(Constant.SHOW_UPDATE);
					  }else{
					myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);}
				}
			}
		
			
		};
	@Override
	public void onClick(View v) { 
		switch (v.getId()) {
		case R.id.chaxuan_btn://查询按钮
			loadWaitPanel();
//			handler.postDelayed(sendable, 0);
			new Thread(sendable).start();
			return;
		case R.id.ll_popup_xuanzhong:
			if(current_xzCheckbox!=null){
			current_xzCheckbox.setChecked(false);}
			xzCheckbox.setChecked(true);
			current_xzCheckbox=xzCheckbox;
			break;
		case R.id.ll_popup_chakan:
			toNoFinish(HBPCheckListActivity.class);
			break;
		case R.id.ll_popup_quxiao:
			break;
		case R.id.quezheng_btn:
			Intent intent = new Intent();
			// 通讯接口
	        intent.setComponent(new ComponentName("com.example.uray.bluetooth.comm.app", "com.example.uray.bluetooth.comm.app.CommActivity"));
	        // 参数配置接口
	        //intent.setComponent(new ComponentName("com.example.uray.bluetooth.comm.app", "com.example.uray.bluetooth.comm.app.ConfigActivity"));
	        intent.setAction(Intent.ACTION_VIEW);   
	        startActivityForResult(intent, 0);  
			break;
			
		}
		dismissPopupWindow();
	}
		
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d(tag, "屏蔽 home,back,menu键keyCode:" + keyCode);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (popupWindow != null && popupWindow.isShowing()) {
				popupWindow.dismiss();
				popupWindow = null;
				return true;
			}
			Log.d(tag, "BACK键捕获。to BACK");
			act.finish();
			act.overridePendingTransition(android.R.anim.slide_in_left,
					android.R.anim.slide_out_right);
			return true;
		}
		if (KeyEvent.KEYCODE_HOME == keyCode) {
			if (popupWindow != null && popupWindow.isShowing()) {
				popupWindow.dismiss();
				popupWindow = null;
				return true;
			}
			Log.d(tag, "home键捕获。to home");
			toHome();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public void onDestroy() {
		dismissPopupWindow();
		super.onDestroy();
	}
//	关闭pop窗口
	private void dismissPopupWindow() {
		if (popupWindow != null && popupWindow.isShowing()) {
			popupWindow.dismiss();
			popupWindow = null;
		}
	}
	
	// 上层应用调用简单，只需要几行代码即可
//		public void onCommButtonClicked(View view)
//		{
//		 
//		}



	// 这里是数据返回的处理，XML格式字符串，具体内容可再行商定
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
              super.onActivityResult(requestCode, resultCode, data); 
	        if(requestCode == 0 && resultCode == RESULT_OK){
	        	String a=data.getStringExtra("return");
	        	MessageTools.showDialogOk(ctx, "返回结果", a);
//	        	Toast.makeText(ctx, a, 1).show();
//	        	textView.setText(data.getStringExtra("return")); 
			// testView显示的即返回参数
	        } 
	    }

	private class ListAdapter extends BaseAdapter {

		public int getCount() {
//			Log.d(tag, "列表的大小" + functionList.size());
//			return functionList.size();
			return infoList.size();
		}

		public Object getItem(int position) {
//			return functionList.get(position);
			return infoList.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			LayoutInflater inflater = LayoutInflater.from(act);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.hbp_screen_item, null);
//				holder.dangan_num_tv = (ImageView) convertView
//						.findViewById(R.id.iv_function_icon);
				holder.dangan_num_tv = (TextView) convertView
						.findViewById(R.id.dangan_num_tv);
				holder.name_tv = (TextView) convertView
						.findViewById(R.id.name_tv);
				holder.sex_tv = (TextView) convertView
						.findViewById(R.id.sex_tv);
				
				
				
				holder.age_tv = (TextView) convertView
						.findViewById(R.id.age_tv);
				holder.shengfenzheng_tv = (TextView) convertView
						.findViewById(R.id.shengfenzheng_tv);
				holder.lastcheck_date_tv = (TextView) convertView
						.findViewById(R.id.lastcheck_date_tv);
				holder.lastcheck_doc_tv = (TextView) convertView
						.findViewById(R.id.lastcheck_doc_tv);
				holder.xueya_left_tv = (TextView) convertView
						.findViewById(R.id.xueya_left_tv);
				holder.xueya_right_tv = (TextView) convertView
						.findViewById(R.id.xueya_right_tv);
				holder.check_cishu_tv = (TextView) convertView
						.findViewById(R.id.check_cishu_tv);
				holder.isgaowei_tv = (TextView) convertView
						.findViewById(R.id.isgaowei_tv);				
				
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

//			holder.iv_function_icon.setImageResource(functionList.get(position)
//					.getImgId());
			holder.dangan_num_tv.setText(infoList.get(position)
					.getsNo());
			holder.name_tv.setText(infoList.get(position)
					.getsPersonName());
			holder.sex_tv.setText(infoList.get(position)
					.getsSexName());
			
			holder.age_tv.setText(CommonUtil.calcAge2(infoList.get(position)
					.getdBirthday())+"");
			holder.shengfenzheng_tv.setText(infoList.get(position)
					.getsCardNo());
			holder.lastcheck_date_tv.setText(CommonUtil.String2date(infoList.get(position)
					.getdCheckTime()));
			holder.lastcheck_doc_tv.setText(infoList.get(position)
					.getsHeadDoctorName());
			holder.xueya_left_tv.setText(infoList.get(position)
					.getdBloodPressureLeftL()+"/"+infoList.get(position)
					.getdBloodPressureLeftH());
			holder.xueya_right_tv.setText(infoList.get(position)
					.getdBloodPressureRightL()+"/"+
					infoList.get(position).getdBloodPressureRightH());
			holder.check_cishu_tv.setText(infoList.get(position)
					.getHealthyCheckUpCount());
			holder.isgaowei_tv.setText("0".equals(infoList.get(position)
					.getHighRisk())?"否":"是");
			
			return convertView;
		}
	}

	static class ViewHolder {
//		ImageView iv_function_icon;
		TextView dangan_num_tv, name_tv,sex_tv
		,age_tv,shengfenzheng_tv,lastcheck_date_tv,lastcheck_doc_tv
		,xueya_left_tv,xueya_right_tv,check_cishu_tv,isgaowei_tv;
	}
}
